package com.cqs.leetcode.math;

public class AddBinary67 {

    public String addBinary(String a, String b) {
        if (a.length() < b.length()) {
            String tmp = a;
            a = b;
            b = tmp;
        }
        char[] acs = a.toCharArray();
        char[] bcs = b.toCharArray();
        int l1 = a.length();
        int l2 = b.length();
        int dlt = l1 - l2;
        int[] result = new int[l1 + 1];
        for (int i = l1 - 1; i >= 0; i--) {
            int c1 = acs[i] - '0';
            int c2 = 0;
            if (i - dlt >= 0) {
                c2 = bcs[i - dlt] - '0';
            }
            //是否进位
            result[i] = (result[i + 1] + c1 + c2) / 2;
            result[i + 1] = (result[i + 1] + c1 + c2) & 1;
        }
        char[] cs = new char[result[0] == 0 ? result.length - 1 : result.length];
        int i = result[0] == 0 ? 1 : 0;
        for (int j = 0; j < cs.length; j++) {
            cs[j] = (char) (result[i+j] + '0');
        }
        return new String(cs);
    }

    public static void main(String[] args) {
        String[] cs = new String[2];
        cs[0] = "1111";
        cs[1] = "1111";
        AddBinary67 addBinary67 = new AddBinary67();
        String s = addBinary67.addBinary(cs[0], cs[1]);
        System.out.println("结果：" + s);

        String a = "12345";
        System.out.println(a.toCharArray()[4]);
    }
}
